// ignore_for_file: overridden_fields, avoid_renaming_method_parameters

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart' as getx;
import '../../../../app_session.dart';
import '../../../routes/app_pages.dart';
import '../../toast_util.dart';
import '../http_exceptions.dart';


/// 错误处理拦截器
class ErrorInterceptor extends Interceptor {

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    ToastUtil.dismiss();
    if (response.data is String) {
      String res = response.data;
      Map<String, dynamic> map = jsonDecode(res);
      if (map.isNotEmpty) {
        response.data = map;
      } else {
        ToastUtil.show(res);
      }
    }
    if (response.data is Map) {
      Map<String, dynamic> resMap = response.data as Map<String, dynamic>;
      if (resMap['code'] == 401) {
        if (getx.Get.isDialogOpen == false) {
          if (!app.isLogin()) return;
          getx.Get.dialog(
              CupertinoAlertDialog(
                title: Text('提示'.tr),
                content: Text('登录过期,请重新登录'.tr),
                actions: [
                  CupertinoDialogAction(child: Text('确认'.tr), onPressed: () {
                    app.logout();
                    getx.Get.offNamed(Routes.LOGIN);
                  },),
                ],
              )
          );
          logger.e(resMap);
          return;
        }
      }
      if (resMap['code'] != 200) {
        // String errorCode = resMap['code'].toString();
        // String errorMsg = resMap['msg'];
        logger.e(response.requestOptions.path);
        ToastUtil.show(resMap.toString());
      }
    }
    handler.next(response);
  }


  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (app.isNetworkOK.value == false) {
      ToastUtil.show('网络不佳');
    }
    if (err.type == DioExceptionType.receiveTimeout
        || err.type == DioExceptionType.connectionTimeout) {
      ToastUtil.show('连接服务器超时');
    }
    super.onError(err, handler);
  }

}
